<div class="modal-category-selector">
    <!-- 已选分类标签显示区域 -->
    <div class="selected-categories mb-2">
        <div class="selected-tags" id="selected-category-tags-{{ name }}">
            <!-- 已选分类标签将在这里动态显示 -->
        </div>
    </div>
    
    <!-- 打开模态框的按钮 -->
    <button type="button" class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#categoryModal-{{ name }}">
        选择分类
    </button>
    
    <!-- 隐藏的input用于存储选中的值 -->
    <div id="selected-categories-input-{{ name }}">
        {{ hidden_inputs|safe }}
    </div>
    
    <!-- 分类选择模态框 -->
    <div class="modal fade" id="categoryModal-{{ name }}" tabindex="-1" aria-labelledby="categoryModalLabel-{{ name }}" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="categoryModalLabel-{{ name }}">选择分类</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <!-- 搜索框 -->
                    <div class="mb-3">
                        <input type="text" id="category-search-{{ name }}" class="form-control" placeholder="搜索分类...">
                    </div>
                    
                    <!-- 分类树形结构 -->
                    <div class="category-tree" id="category-tree-{{ name }}" style="max-height: 400px; overflow-y: auto;">
                        {{ tree_html|safe }}
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveCategorySelection('{{ name }}')" data-bs-dismiss="modal">确定</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 初始化已选分类
document.addEventListener('DOMContentLoaded', function() {
    initializeCategorySelection('{{ name }}');
});

// 初始化分类选择
function initializeCategorySelection(name) {
    const container = document.getElementById('selected-category-tags-' + name);
    const hiddenInputs = document.querySelectorAll('#selected-categories-input-' + name + ' input');
    
    hiddenInputs.forEach(input => {
        const categoryId = input.value;
        const category = getCategoryById(name, categoryId);
        if (category) {
            addSelectedCategoryTag(name, categoryId, category.name);
        }
    });
}

// 根据ID获取分类信息
function getCategoryById(name, id) {
    // 构建正确的CSS选择器
    const selector = '#category-tree-' + name + ' .category-item[data-id="' + id + '"] .category-label';
    const categoryElement = document.querySelector(selector);
    if (categoryElement) {
        return {
            id: id,
            name: categoryElement.textContent.trim()
        };
    }
    // 如果在当前树中找不到，尝试在已选标签中查找
    const tagSelector = '#selected-category-tags-' + name + ' .category-tag[data-id="' + id + '"]';
    const tagElement = document.querySelector(tagSelector);
    if (tagElement) {
        // 获取标签文本并移除关闭按钮部分
        const tagText = tagElement.textContent || tagElement.innerText;
        // 移除最后的关闭字符（假定是最后几个字符）
        const cleanName = tagText.trim();
        return {
            id: id,
            name: cleanName
        };
    }
    return null;
}

// 分类搜索功能
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('category-search-{{ name }}');
    if (searchInput) {
        searchInput.addEventListener('input', function(e) {
            const searchTerm = e.target.value.toLowerCase();
            const treeItems = document.querySelectorAll('#category-tree-{{ name }} .category-item');
            
            treeItems.forEach(item => {
                const categoryName = item.querySelector('.category-label').textContent.toLowerCase();
                
                if (searchTerm === '') {
                    // 如果搜索词为空，显示所有项目，并展开所有分类
                    item.style.display = '';
                    // 同步更新所有分类的展开状态
                    const toggleButton = item.querySelector('.category-toggle');
                    if (toggleButton && toggleButton.textContent === '+') {
                        const categoryId = item.getAttribute('data-id');
                        const childrenContainer = document.getElementById('children-{{ name }}-' + categoryId);
                        if (childrenContainer) {
                            childrenContainer.style.display = 'none';
                        }
                    } else if (toggleButton && toggleButton.textContent === '−') {
                        const categoryId = item.getAttribute('data-id');
                        const childrenContainer = document.getElementById('children-{{ name }}-' + categoryId);
                        if (childrenContainer) {
                            childrenContainer.style.display = 'block';
                        }
                    }
                } else if (categoryName.includes(searchTerm)) {
                    // 显示匹配的项目
                    item.style.display = '';
                    // 展开所有父级节点
                    let parentId = item.getAttribute('data-parent');
                    while (parentId && parentId !== '0') {
                        const parentItem = document.querySelector('#category-tree-{{ name }} .category-item[data-id="' + parentId + '"]');
                        if (parentItem) {
                            parentItem.style.display = '';
                            const childrenContainer = parentItem.querySelector('.category-children');
                            if (childrenContainer) {
                                childrenContainer.style.display = 'block';
                                const toggleButton = parentItem.querySelector('.category-toggle');
                                if (toggleButton) {
                                    toggleButton.textContent = '−';
                                }
                            }
                            parentId = parentItem.getAttribute('data-parent');
                        } else {
                            break;
                        }
                    }
                } else {
                    // 隐藏不匹配的项目
                    item.style.display = 'none';
                }
            });
            
            // 当搜索词为空时，确保所有分类正确显示其展开/折叠状态
            if (searchTerm === '') {
                // 获取所有切换按钮并同步状态
                const toggleButtons = document.querySelectorAll('#category-tree-{{ name }} .category-toggle');
                toggleButtons.forEach(button => {
                    const categoryId = button.id.replace('toggle-{{ name }}-', '');
                    const childrenContainer = document.getElementById('children-{{ name }}-' + categoryId);
                    if (childrenContainer) {
                        if (button.textContent === '+') {
                            childrenContainer.style.display = 'none';
                        } else if (button.textContent === '−') {
                            childrenContainer.style.display = 'block';
                        }
                    }
                });
            }
        });
    }
});

// 切换分类子项显示/隐藏
function toggleCategoryChildren(name, categoryId) {
    const childrenContainer = document.getElementById('children-' + name + '-' + categoryId);
    const toggleButton = document.getElementById('toggle-' + name + '-' + categoryId);
    
    if (childrenContainer && toggleButton) {
        if (childrenContainer.style.display === 'none' || childrenContainer.style.display === '') {
            childrenContainer.style.display = 'block';
            toggleButton.textContent = '−';
        } else {
            childrenContainer.style.display = 'none';
            toggleButton.textContent = '+';
        }
    }
}

// 保存分类选择
function saveCategorySelection(name) {
    const checkboxes = document.querySelectorAll('#category-tree-' + name + ' input[type="checkbox"]:checked');
    const selectedContainer = document.getElementById('selected-categories-input-' + name);
    const tagsContainer = document.getElementById('selected-category-tags-' + name);
    
    // 清空之前的选择
    selectedContainer.innerHTML = '';
    tagsContainer.innerHTML = '';
    
    // 保存新的选择
    checkboxes.forEach(checkbox => {
        const categoryId = checkbox.value;
        const categoryName = checkbox.nextElementSibling.textContent.trim();
        
        // 添加隐藏的input字段
        const hiddenInput = document.createElement('input');
        hiddenInput.type = 'hidden';
        hiddenInput.name = name;
        hiddenInput.value = categoryId;
        selectedContainer.appendChild(hiddenInput);
        
        // 添加标签
        addSelectedCategoryTag(name, categoryId, categoryName);
    });
}

// 添加已选分类标签
function addSelectedCategoryTag(name, id, categoryName) {
    const tagContainer = document.getElementById('selected-category-tags-' + name);
    const tagExists = tagContainer.querySelector('.category-tag[data-id="' + id + '"]');
    
    if (!tagExists) {
        const tag = document.createElement('span');
        tag.className = 'badge bg-primary me-1 mb-1 category-tag';
        tag.setAttribute('data-id', id);
        tag.innerHTML = `
            ${categoryName}
            <button type="button" class="btn-close btn-close-white ms-1" 
                    onclick="removeCategoryTag('${name}', ${id})" 
                    style="font-size: 0.4rem;"></button>
        `;
        tagContainer.appendChild(tag);
    }
}

// 移除分类标签
function removeCategoryTag(name, id) {
    // 移除标签
    const tag = document.querySelector('#selected-category-tags-' + name + ' .category-tag[data-id="' + id + '"]');
    if (tag) {
        tag.remove();
    }
    
    // 移除隐藏的input字段
    const hiddenInput = document.querySelector('#selected-categories-input-' + name + ' input[value="' + id + '"]');
    if (hiddenInput) {
        hiddenInput.remove();
    }
    
    // 取消模态框中的勾选
    const modalCheckbox = document.querySelector('#categoryModal-' + name + ' input[value="' + id + '"]');
    if (modalCheckbox) {
        modalCheckbox.checked = false;
    }
}
</script>